package dyyx.agent;
import java.util.Date;
import java.util.List;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

public class ClientMain {

	public static void main(String[] args) throws Exception {
		System.out.println("agent client,"+new Date());
		
		System.out.println("list");
		System.out.println("attach pid agentpath");
		
		int argsnum = 0;
		if(args!=null){
			argsnum = args.length;
		}
		System.out.println("argsnum="+argsnum);

		
		if(argsnum !=1 && argsnum!=3){
			System.out.println("args error,argsnum="+argsnum);
			return;
		}
		
		String cmd = args[0];
		
		if("list".equals(cmd)){		
			
			List<VirtualMachineDescriptor> list = VirtualMachine.list();
			for (VirtualMachineDescriptor vmd : list) {
                System.out.println(vmd);
            }		
			return;
		}
		
		if("attach".equals(cmd)){
			
			if(argsnum!=3){
				System.out.println("args error");
				return;
			}
			String pid = args[1];
			String agentpath = args[2];
			
			List<VirtualMachineDescriptor> list = VirtualMachine.list();
			VirtualMachineDescriptor vmd = null;
			
			for (VirtualMachineDescriptor item : list) {
				if(item.id().toString().equals(pid)){
					vmd=item;
					break;
				}
            }
			
			if(vmd==null){
				System.out.println("jvm process not exist,pid="+pid);
				return;
			}
			
			VirtualMachine vm = VirtualMachine.attach(vmd.id());
            vm.loadAgent(agentpath);	
            
            System.out.println("loadAgent done,"+new Date());
            
            vm.detach();
            
            return;
			
			
		}
		
		System.out.println("args error,cmd="+cmd);

		
		

		
	}
}
